package com.cx.util;

import java.io.*;

/**
 * @author cxx
 * @create 2021-03-24 15:49
 **/
public class SerializableTest {


    public static class Demo1 implements Serializable{

        private static final long serialVersionUID = 115165165116511L;

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }



    public static void main(String[] args) {
        Demo1 demo1 = new Demo1 ();
        demo1.setName ("aaa");
        byte[] obs = serialize(demo1);
        com.cx.util.Demo1 demo2 = unserialize (com.cx.util.Demo1.class, obs);
        System.out.println (demo2.getName ());
    }


    public static byte[] serialize(Serializable serializable){
        ByteArrayOutputStream baos = new ByteArrayOutputStream ();
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream (baos);
            objectOutputStream.writeObject (serializable);
            objectOutputStream.flush ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        return baos.toByteArray ();
    }

    public static <T> T unserialize(Class<T> tClass,byte[] bytes){
        ByteArrayInputStream bais = new ByteArrayInputStream (bytes);
        try (ObjectInputStream objectInputStream = new ObjectInputStream (bais){
                @Override
                protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                    Class<?> aClass = super.resolveClass (desc);
                    return aClass == Demo1.class ? com.cx.util.Demo1.class:aClass;
                }
        }){
            return (T) objectInputStream.readObject ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return null;
    }

}
